import React, { useEffect, useState, useRef } from "react";
import Draggable from "./Draggable";
import Sidebar from "./Sidebar";

import GamepadController from "../utils/GamepadController.js";
import { MODE_EDIT_CONFIG, BUTTON_LS, BUTTON_RS } from "../utils/constants.js";

import clickImg from "../assets/click.png";
import leftImg from "../assets/left.png";
import rightImg from "../assets/right.png";
import Button from "./Button.jsx";

const Configurator = ({ config, saveGameConfig }) => {
  const parentRef = useRef(null);
  const [parentSize, setParentSize] = useState({ width: 0, height: 0 });
  const [virtualButtons, setVirtualButtons] = useState([]);
  const [keyCode, setKeyCode] = useState([]);
  useEffect(() => {
    const controller = GamepadController.getInstance();
    // 注册编辑模式事件处理器
    controller.registerModeEventHandler(MODE_EDIT_CONFIG, gamepadHandler);
    // 从props获取配置
    if (config?.buttons) {
      setVirtualButtons(config.buttons);
    }

    // 初始化父容器尺寸
    if (parentRef.current) {
      const { clientWidth, clientHeight } = parentRef.current;
      setParentSize({ width: clientWidth, height: clientHeight });
    }

    // 创建ResizeObserver监听父容器尺寸变化
    const resizeObserver = new ResizeObserver(entries => {
      for (const entry of entries) {
        const { clientWidth, clientHeight } = entry.target;
        setParentSize({ width: clientWidth, height: clientHeight });
      }
    });

    if (parentRef.current) {
      resizeObserver.observe(parentRef.current);
    }

    return () => {
      if (resizeObserver) {
        resizeObserver.disconnect();
      }
    };
  }, [config]);

  useEffect(() => {
    if (keyCode.length === 0) {
      return;
    }
    setVirtualButtons([...updateActiveButtonKeyCode(keyCode)]);
    setKeyCode([]);
  }, [keyCode]);

  const gamepadHandler = (e) => {
    if (e.eventType == "connect") {
      onGamepadConnect(e);
    } else if (e.eventType == "press") {
      onGamepadButtonPress(e);
    } else if (e.eventType == "release") {
      onGamepadButtonRelease(e);
    }
  };

  const onGamepadConnect = (e) => {
    const { id } = e.gamepad;
    console.log(`${id} connected!`);
  };
  const onGamepadButtonPress = (e) => {
    const { buttonName, index } = e.detail;
  };

  const onGamepadButtonRelease = (e) => {
    const { buttonName, index } = e.detail;
    const specialKeyIndices = [8, 9];
    if (specialKeyIndices.includes(index)) {
      return;
    }
    setKeyCode(e.detail.index);
  };

  const createBtn = (type = "click") => {
    const pos = { x: 0, y: 0 };
    if (type === "click") {
      pos.x = parentSize.width / 2;
    pos.y = parentSize.height / 2;
    } else if (type === "left_stick") {
      pos.x = parentSize.width / 4;
      pos.y = (parentSize.height / 4) * 3;
      pos.radius = 50;
    } else if (type === "right_stick") {
      pos.x = (parentSize.width / 4) * 3;
      pos.y = (parentSize.height / 4) * 3;
      pos.radius = 50;
    }
    return {
      type,
      ...pos,
      key: `btn_${Date.now()}`,
      active: true,
      mode: type.includes('stick') ? 'move' : undefined,
    };
  };
  const addClickButton = () => {
    setVirtualButtons([...updateActiveButton(-1), createBtn("click")]);
  };

  const addJoystick = (type = "left") => {
    setVirtualButtons([...updateActiveButton(-1), createBtn(`${type}_stick`)]);
  };

  const updateActiveButton = (index) => {
    return virtualButtons.map((btn, i) => ({
      ...btn,
      active: i === index,
    }));
  };

  const updateActiveButtonKeyCode = (keycode) => {
    return virtualButtons.map((btn) => {
      // 仅处理类型为'click'的按钮
      if (btn.type !== "click") {
        return btn;
      }

      // 对于激活状态的按钮，更新其keycode
      if (btn.active) {
        return {
          ...btn,
          keycode: keycode.toString(),
        };
      }
      // 对于非激活状态但keycode匹配的按钮，清除keycode
      else if (btn.keycode === keycode.toString() && !btn.active) {
        return {
          ...btn,
          keycode: null,
        };
      }

      return btn;
    });
  };

  const handlePointer = (index) => {
    const newButtons = [...updateActiveButton(index)];
    setVirtualButtons(newButtons);
  };

  const handleDrag = (index, e, data) => {
    const newButtons = [...updateActiveButton(index)];
    newButtons[index] = { ...newButtons[index], x: data.x, y: data.y };
    setVirtualButtons(newButtons);
  };

  const generateConfig = () => {
    const buttons = virtualButtons.filter(
      (btn) => btn.keycode !== null
    );

    const configJson = {
    ...config,
    resolution: {
      width: parentSize.width,
      height: parentSize.height
    },
    buttons: buttons.map(btn => ({...btn, mode: btn.mode || 'move', radius: btn.radius || 50})),
  };
    saveGameConfig(configJson);
  };

  const btnList = [
    {
      name: "点击",
      icon: clickImg,
      clickHandler: () => {
        addClickButton();
      },
    },
    {
      name: "左摇杆",
      icon: leftImg,
      keycode: BUTTON_LS,
      clickHandler: () => {
        addJoystick("left");
      },
    },
    {
      name: "右摇杆",
      icon: rightImg,
      keycode: BUTTON_RS,
      clickHandler: () => {
        addJoystick("right");
      },
    },
  ];

  return (
    <div ref={parentRef} className="absolute inset-0 bg-black/50">
        <Sidebar list={btnList} generateConfig={generateConfig} />
        <div className="w-full h-full">
          {virtualButtons.map((btn, index) => (
            <Draggable center={true}
              key={btn.key}
              position={{ x: btn.x, y: btn.y }}
              hasSetting={btn.type !== "click"}
              onDrag={(e, data) => handleDrag(index, e, data)}
              onPointer={(e) => handlePointer(index)}
              onDelete={() => {
              setVirtualButtons(virtualButtons.filter((b) => b.key !== btn.key));
            }}
            onSettings={() => {
              const newMode = btn.mode === 'move' ? 'skill' : btn.mode === 'skill' ? 'view' : 'move';
              setVirtualButtons(virtualButtons.map(b => 
                b.key === btn.key ? { ...b, mode: newMode } : b
              ));
            }}
            >
              <Button keycode={btn.keycode} type={btn.type} mode={btn.mode} active={btn.active} />
            </Draggable>
          ))}
        </div>
    </div>
  );
};

export default Configurator;

